import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get_utils/src/get_utils/get_utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:smart_devices/bruno/src/components/actionsheet/brn_common_action_sheet.dart';
import 'package:smart_devices/bruno/src/components/picker/brn_multi_picker.dart';
import 'package:smart_devices/bruno/src/theme/base/brn_text_style.dart';
import 'package:smart_devices/bruno/src/theme/configs/brn_picker_config.dart';
import 'package:smart_devices/constant/assets.dart';
import 'package:smart_devices/utils/styles.dart';

import 'colors.dart';

typedef SelectedImage = void Function(List<XFile> res);

class ToolsUtils {
  ToolsUtils._();

  static TextEditingController editingController(String content) {
    TextEditingController textEditingController =
        TextEditingController(text: content);
    // textEditingController.text = content;
    textEditingController.value = TextEditingValue(
        text: content,
        selection: TextSelection.fromPosition(TextPosition(
            affinity: TextAffinity.downstream, offset: content.length)));
    return textEditingController;
  }

  static SvgPicture assetImageSvg(
    String assetName, {
    BoxFit fit = BoxFit.cover,
    double? width,
    double? height,
  }) {
    if (!assetName.endsWith('.svg')) {
      assetName = '$assetName.svg';
    }
    return SvgPicture.asset(
      '${Assets.svgUrl}/$assetName',
      width: width,
      height: height,
      fit: fit,
    );
  }

  static SvgPicture urlSvg(String url,
      {double? width, double? height, BoxFit fit = BoxFit.contain}) {
    return SvgPicture.network(url, width: width, height: height, fit: fit);
  }

  static AssetImage assetImageIcon(String assetName) {
    return AssetImage('${Assets.iconUrl}/$assetName');
  }

  static Image image(
    String assetName, {
    BoxFit? fit,
    double? width,
    double? height,
  }) {
    return Image.asset(
      '${Assets.imgUrl}/$assetName',
      fit: fit,
      width: width,
      height: height,
    );
  }

  static AssetImage assetImage(String assetName) {
    return AssetImage(
      '${Assets.imgUrl}/$assetName',
    );
  }

  static Image urlImg(String url, {double? width, double? height}) {
    return Image.network(
      url,
      width: width,
      height: height,
    );
  }

  static void openGalleryOrCamera(
      BuildContext context, SelectedImage? gallery, SelectedImage? camera,
      [int count = 10]) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BrnCommonActionSheet(
            title: '选择照片或者拍照',
            cancelTitle: '取消',
            actions: [
              BrnCommonActionSheetItem('打开相册，选取照片',
                  titleStyle: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333)),
              BrnCommonActionSheetItem('打开相机拍照',
                  titleStyle: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333)),
            ],
            clickCallBack: (int index, BrnCommonActionSheetItem item) {
              if (index == 0) {
                openGalleryImage(gallery, count);
              } else if (index == 1) {
                openCameraImage(camera);
              }
            },
          );
        });
  }

  static void openGalleryImage(SelectedImage? gallery, [int count = 10]) async {
    final ImagePicker picker = ImagePicker();
    List<XFile>? res = await picker.pickMultiImage(limit: count);
    if (res.isNotEmpty) {
      gallery!(res);
    }
  }

  static void openCameraImage(SelectedImage? camera) async {
    final ImagePicker picker = ImagePicker();
    XFile? res = await picker.pickVideo(source: ImageSource.camera);
    if (res != null) {
      camera!([res]);
    }
  }

  static Future<void> openCupertinoModalPopup(
      BuildContext context, SelectedImage gallery, SelectedImage camera) async {
    final cupertinoTheme = CupertinoTheme(
        data: const CupertinoThemeData(barBackgroundColor: Colors.white),
        child: CupertinoActionSheet(
          actions: [
            Container(
              color: Colors.white,
              child: CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, 1);
                },
                child: Text('拍照',
                    style: StylesUtils.customTextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: '#409eff')),
              ),
            ),
            Container(
              color: Colors.white,
              child: CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, 2);
                },
                child: Text(
                  '手机相册选取',
                  style: StylesUtils.customTextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: '#409eff'),
                ),
              ),
            )
          ],
          cancelButton: CupertinoActionSheetAction(
            isDestructiveAction: true,
            onPressed: () {
              Navigator.pop(context, 0);
            },
            child: Text(
              '取消',
              style: StylesUtils.customTextStyle(
                  fontSize: 20, fontWeight: FontWeight.bold, color: '#409eff'),
            ),
          ),
        ));
    int? result = await showCupertinoModalPopup<int>(
        context: context,
        barrierColor: Colors.black54,
        semanticsDismissible: true,
        builder: (BuildContext context) => cupertinoTheme);
    if (result == 1) {
      /// 相机
      openCameraImage((List<XFile> res) {
        gallery.call(res);
      });
    } else if (result == 2) {
      /// 相册
      openGalleryImage((List<XFile> res) {
        camera.call(res);
      }, 1);
    }
  }

  static void openDataPicker(
      BuildContext context,
      List<BrnMultiDataPickerEntity> data,
      ConfirmButtonClick confirmButtonClick,
      {String title = '请选择'}) {
    BrnMultiDataPicker(
      context: context,
      delegate: BrnDefaultMultiDataPickerDelegate(data: data),
      confirmClick: confirmButtonClick,
      title: title,
      titleTextStyle: StylesUtils.customTextStyle(
          color: ColorsUtils.color3333,
          fontSize: 16,
          fontWeight: FontWeight.w600),
      cancelTextStyle: StylesUtils.customTextStyle(
          color: ColorsUtils.color3333, fontSize: 16),
      confirmTextStyle: StylesUtils.customTextStyle(
          color: ColorsUtils.colorFf6e, fontSize: 16),
      themeData: BrnPickerConfig(
          cornerRadius: 15,
          titleHeight: 50,
          dividerColor:
              ColorsUtils.parseColorFromHexString(ColorsUtils.colorD7d7),
          itemHeight: 40,
          itemTextSelectedStyle: BrnTextStyle(
              fontWeight: FontWeight.w700,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
              fontSize: 15),
          itemTextStyle: BrnTextStyle(
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color7979),
              fontWeight: FontWeight.normal,
              fontSize: 14)),
    ).show();
  }

  static Future<List<PlatformFile>?> openPickerFile(
      List<String>? allowedExtensions) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: FileType.custom,
        allowedExtensions: allowedExtensions);
    if (result != null) {
      // return result.paths.map((path) => File(path!)).toList();
      return result.files;
    }
    return null;
  }

  static bool isZip(String filePath) {
    var ext = filePath.toLowerCase();
    return ext.endsWith(".zip") ||
        ext.endsWith(".rar") ||
        ext.endsWith(".arj") ||
        ext.endsWith(".jar") ||
        ext.endsWith(".lzh") ||
        ext.endsWith(".7z") ||
        ext.endsWith(".dar");
  }

  static AssetImage getFileIconByFilename(String name) {
    if (GetUtils.isImage(name)) {
      return ToolsUtils.assetImageIcon('img.png');
    }
    if (GetUtils.isWord(name)) {
      return ToolsUtils.assetImageIcon('docx.png');
    }
    if (GetUtils.isExcel(name)) {
      return ToolsUtils.assetImageIcon('xlsx.png');
    }
    if (GetUtils.isPPT(name)) {
      return ToolsUtils.assetImageIcon('pptx.png');
    }
    if (GetUtils.isPDF(name)) {
      return ToolsUtils.assetImageIcon('pdf.png');
    }
    if (ToolsUtils.isZip(name)) {
      return ToolsUtils.assetImageIcon('zip.png');
    }
    return ToolsUtils.assetImageIcon('img.png');
  }

  static Future<PackageInfo> appInfo() async {
    return await PackageInfo.fromPlatform();
  }
}
